package com.emperor.util;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.List;
import java.util.Map;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperPrintManager;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
import net.sf.jasperreports.view.JasperViewer;

import org.apache.log4j.Logger;

import com.emperor.core.app.AppConstant;
import com.emperor.core.logic.ReportDataSource;

public class ReportUtil {

	public static Logger log = Logger.getLogger(ReportUtil.class);
	
	public static void runReceiptPrint(String reportFile, Map params, ReportDataSource dataSource, int mode) {
		try {
			File file = new File(reportFile);
			JasperDesign jasperDesign = JRXmlLoader.load(file);
			JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
			JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, dataSource);
			
			if (mode == AppConstant.VIEW_REPORT) {
				JasperViewer.viewReport(jasperPrint, false);	
			} else {
				JasperPrintManager.printReport(jasperPrint, false);	
			}
		} catch(Exception e) {
			log.error("Unable to generate report.", e);
		}
	}
	
	public static void runReport(String dbname, String username, String password, String reportFile, Map params) {
		try {
			File file = new File(reportFile);
			JasperDesign jasperDesign = JRXmlLoader.load(file);
			JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
			Class.forName("com.mysql.jdbc.Driver");
			Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/" + dbname, username, password);
			JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, connection);
			JasperViewer.viewReport(jasperPrint, false);
		} catch(Exception e) {
			log.error("Report util error.", e);
		}
	}
	
	public static void report(String reportFile) {
		report(reportFile, null);
	}
	
	public static void report(String reportFile, Map params) {
		runReport("emperor", "root", "password", reportFile, params);
	}
}
